package com.ktkj.init.controller;

import com.alibaba.excel.EasyExcel;
import com.ktkj.init.constant.FileConstant;
import com.ktkj.init.constant.ModelConstant;
import com.ktkj.init.dto.DictCondition;
import com.ktkj.init.dto.DictForm;
import com.ktkj.init.dto.DictImportForm;
import com.ktkj.init.dto.DictListTreeCondition;
import com.ktkj.init.entity.Attachment;
import com.ktkj.init.entity.Dict;
import com.ktkj.init.exception.BusinessException;
import com.ktkj.init.response.Response;
import com.ktkj.init.response.ResponseCallBack;
import com.ktkj.init.response.ResponseCriteria;
import com.ktkj.init.service.AttachmentService;
import com.ktkj.init.service.DictService;
import com.ktkj.init.service.listener.DictDataListener;
import com.ktkj.init.vo.QueryResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 字典管理.
 *
 * @author :yanlixiong
 * @date :2021-06-29 11:36:32
 */
@Api(tags = "字典管理")
@RestController
@RequestMapping("/dict")
public class DictController {

    @Resource
    private DictService dictService;

    @Resource
    private AttachmentService attachmentService;

    @Value("${upload.file.path}")
    private String filePath;

    @ApiOperation(value = "详情")
    @GetMapping(path = "/getById")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id", example = "1", required = true)})
    public Response getById(@RequestParam final Long id) {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                Dict bean = dictService.getById(id);
                if (bean == null) {
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, "id错误，没有查询到对应数据！");
                }
                dictService.getChildrenList(bean, "");
                criteria.addSingleResult(bean);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "列表")
    @GetMapping(path = "/list")
    public Response list(@Validated @ModelAttribute final DictCondition condition) {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                QueryResult<Dict> queryList = dictService.page(condition);
                criteria.addSingleResult(queryList);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "列表（树形结构）")
    @GetMapping(path = "/listTree")
    public Response listTree(@Validated @ModelAttribute final DictListTreeCondition condition) {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                criteria.addSingleResult(dictService.listTree(condition));
            }
        }.sendRequest();
    }

    @ApiOperation(value = "获取字典目录")
    @GetMapping(path = "/getDictDir")
    public Response getDictDir() {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                criteria.addSingleResult(dictService.getDictDir());
            }
        }.sendRequest();
    }


    @ApiOperation(value = "根据类型和父id查询")
    @GetMapping(path = "/getByTypeAndPId")
    public Response getByTypeAndPId(@Validated @ModelAttribute final DictCondition condition) {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                List<Dict> queryList = dictService.getByTypeAndPId(condition);
                criteria.addSingleResult(queryList);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "保存（增加/修改）")
    @PostMapping(path = "/saveOrUpdate")
    public Response saveOrUpdate(@Validated @ModelAttribute final DictForm form) {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                Dict bean = dictService.saveOrUpdate(form);
                criteria.addSingleResult(bean);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "批量删除")
    @PostMapping(path = "/batchDelete")
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "id集合（多个id用,隔开）", example = "1,2,3", required = true)})
    public Response batchDelete(@RequestParam final String ids) {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                List<Long> idList = Arrays.asList(ids.trim().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                dictService.removeJudge(idList);
                dictService.removeByIds(idList);
                criteria.addSingleResult(true);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "批量导入")
    @PostMapping(path = "/batchImport", headers = "content-type=multipart/form-data")
    public Response batchImport(@RequestPart("file") final MultipartFile file) {
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                if (!FileConstant.FILE_SUFFIX_XLSX.equals(suffix)) {
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, "文件格式错误，不是" + FileConstant.FILE_SUFFIX_XLSX + "格式！");
                }
                Attachment attachment = attachmentService.uploadFileLocalPath(file, fileName, ModelConstant.MODE_DICT);
                try {
                    EasyExcel.read(filePath+attachment.getPath(), DictImportForm.class, new DictDataListener(dictService)).sheet().doRead();
                } catch (Exception e) {
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, e.getMessage());
                }
                criteria.addSingleResult(true);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "批量导出")
    @GetMapping(path = "/batchExport")
    public void batchExport(@Validated @ModelAttribute final DictCondition condition, final HttpServletResponse response) {
        dictService.batchExport(condition, response);
    }

}
